import path from 'path';

const relativePathPrefixRegExp = /^\.\.?\//;

/**
 * 返回两个绝对路径之间的相对路径
 * @param from 目前的绝对路径
 * @param to 前往的绝对路径
 * @param addPrefix 时候要加前缀：`./`
 * @param isAbsoluteCallback 如果返回的绝对路径则执行这个回调
 */
export function relative(from: string, to: string, addPrefix = false, isAbsoluteCallback?: () => void) {
	let _path = path.relative(from, to);

	// 返回的不是绝对路径才做操作
	if (!path.isAbsolute(_path)) {
		_path = _path.replace(/\\/g, '/');

		if (addPrefix && !relativePathPrefixRegExp.test(_path)) {
			_path = './' + _path;
		}
	} else {
		isAbsoluteCallback && isAbsoluteCallback();
	}

	return _path;
}

export function relative_join(addPrefix: boolean, ...paths: string[]) {
	let _path = path.join(...paths);

	// 替换 \
	_path = _path.replace(/\\/g, '/');
	// 添加前缀
	if (addPrefix) {
		_path = './' + _path;
	}

	return _path;
}
